<?php


namespace app\services\user;


use app\models\coupon\CouponModel;
use app\models\coupon\UserCouponModel;
use app\services\BaseService;
use zjkal\TimeHelper;

class UserCouponService extends BaseService
{

    protected static function initModel()
    {
        return new UserCouponModel();
    }

    /**
     * 检测优惠券是否可领
     * @param $userId
     * @param $couponInfo
     * @return int
     * @throws \Exception
     */
    public static function checkCouponCanGet($userId, $couponInfo)
    {
        try {
            if ($couponInfo['send_type'] == 1 && $couponInfo['residue_num'] == 0) {
                return 0;
            }
            if ($couponInfo['limit_type'] == 1) {
                // 已领次数
                $userCount = self::initModel()
                    ->where('user_id', $userId)
                    ->where('coupon_id', $couponInfo['id'])
                    ->count('id');
                if ($userCount < $couponInfo['limit_num']) {
                    return $couponInfo['amount'];
                }
                return 0;
            }
            if ($couponInfo['limit_type'] == 2) {
                // 今天是否领取
                $userCouponTime = self::initModel()
                    ->where('user_id', $userId)
                    ->where('coupon_id', $couponInfo['id'])
                    ->max('create_time');

                if (!$userCouponTime || !TimeHelper::isToday($userCouponTime)) {
                    return $couponInfo['amount'];
                }
                return 0;
            }
            return $couponInfo['amount'];
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 发放优惠券
     * @param array $uidArr
     * @param int $couponId
     * @return bool
     * @throws \Exception
     */
    public static function sendCoupon(array $uidArr, int $couponId): bool
    {
        try {
            $couponInfo = CouponModel::find($couponId);
            if ($couponInfo['status'] == 1) {
                throw new \Exception('优惠券已关闭');
            }
            if ($couponInfo->getData('start_time') > time()) {
                throw new \Exception('优惠券未到发放时间');
            }
            if ($couponInfo->getData('end_time') < time()) {
                throw new \Exception('优惠券发放已结束');
            }
            if ($couponInfo['send_type'] == 1 && $couponInfo['residue_num'] < count($uidArr)) {
                throw new \Exception('优惠券数量不足');
            }
            if ($couponInfo['time_type'] == 1) {
                $useStartTime = time();
                $useEndTime = time() + $couponInfo['use_day'] * 86400;
            } else {
                $useStartTime = $couponInfo->getData('use_start_time');
                $useEndTime = $couponInfo->getData('use_end_time');
            }
            $dataAll = [];
            foreach ($uidArr as $k => $uid) {
                $dataAll[$k] = [
                    'user_id' => $uid,
                    'coupon_id' => $couponInfo['id'],
                    'coupon_name' => $couponInfo['coupon_name'],
                    'amount' => $couponInfo['amount'],
                    'less_amount' => $couponInfo['less_amount'],
                    'use_start_time' => $useStartTime,
                    'use_end_time' => $useEndTime,
                    'use_type' => $couponInfo['use_type'],
                    'type_id' => $couponInfo['type_id'],
                ];
            }
            $model = new UserCouponModel();
            $model->saveAll($dataAll);
            if ($couponInfo['send_type'] == 1) {
                $couponInfo->have_send_num = $couponInfo['have_send_num'] + 1;
                $couponInfo->residue_num = $couponInfo['residue_num'] - 1;
                $couponInfo->save();
            }
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
}